const { LinValidator, Rule } = require('../../core/lin-validator')
const User = require('../../db/model/user')
const { loginType } = require('../lib/login-type')

class PositiveIntegerValidator extends LinValidator {
  constructor () {
    super()
    this.id = [
      new Rule('isInt', '需要正整数', {min: 1})
    ]
  }
}

class RegisterValidator extends LinValidator {
  constructor () {
    super()
    this.email = [
      new Rule('isEmail', '格式不正确')
    ]
    this.password1 = [
      new Rule('isLength', '请输入6~12位密码', {min: 6, max: 12}),
      new Rule('matches', '密码格式不正确', '^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]')
    ]
    this.nickname = [ new Rule('isLength', '请输入4~18位昵称', {min: 4, max: 18}) ]
  }

  validatePassword(vals) {
    const pwd1 = vals.body.password1
    const pwd2 = vals.body.password2
    if (pwd1 !== pwd2) {
      throw new Error('两次输入的密码不相同')
    }
  }

  async validateEmail(vals) {
    const email = vals.body.email
    const user = await User.findOne({
      where: {
        email: email
      }
    })
    if (user) {
      throw new Error('Email已被注册')
    }
  }
}

class TokenValidator extends LinValidator {
  constructor() {
    super()
    this.account = [
      new Rule('isLength', '长度应在4~32之间', { min: 4, max: 32})
    ]
    this.secret = [
      new Rule('isOptional'),
      new Rule('isLength', '长度应该大于6字符', { min: 6, max: 128})
    ]
  }

  validateLoginType(vals) {
    const type = vals.body.type
    if (!type) {
      throw new Error('type为必填参数')
    }
    if (!loginType[type]) {
      throw new Error('该type不存在')
    }
  }
}

class NotEmptyValidator extends LinValidator {
  constructor() {
    super()
    this.token = [
      new Rule('isLength', 'token不能为空', {min: 1})
    ]
  }
}

module.exports = {
  PositiveIntegerValidator,
  RegisterValidator,
  TokenValidator,
  NotEmptyValidator
}